package com.zhongli.devplatform.security.weixin;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.zhongli.devplatform.service.imp.user.UserRegisterService;
import com.zhongli.devplatform.service.imp.sys.ReadSystemParameterService;
import com.zhongli.devplatform.component.SpringUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class WeixinAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {


    public WeixinAuthenticationProcessingFilter() {
        super(new AntPathRequestMatcher("/weixin/login"));
    }

    @SneakyThrows
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {

        String weixinLoginType = SpringUtil.getBean(ReadSystemParameterService.class).getSystemParameter("weixin_login_type");
        String weixinId = null;
        String code = request.getParameter("code");
        String rawData = request.getParameter("rawData");
        String signature = request.getParameter("signature");
        String encrypteData = request.getParameter("encrypteData");
        String iv = request.getParameter("iv");

        if (weixinLoginType.equals("1")) {

            WxMaService wxService = SpringUtil.getBean(WxMaService.class);
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            weixinId = session.getOpenid();

            logger.info("session.getSessionKey()：" + session.getSessionKey());
            logger.info("encrypteData：" + encrypteData);
            logger.info("iv：" + iv);

            try {
                WxMaUserInfo wxMaUserInfo = wxService.getUserService().getUserInfo(session.getSessionKey(), encrypteData, iv);
                UserRegisterService weixinRegisterService = SpringUtil.getBean(UserRegisterService.class);
                //weixinRegisterService.register(wxMaUserInfo);

            } catch (Exception e) {
                log.error("微信自动注册失败：" + e.getMessage());
                e.printStackTrace();
            }

            request.setAttribute("weixinId", weixinId);

        } else {

            WxMpService wxService = SpringUtil.getBean(WxMpService.class);
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxService.oauth2getAccessToken(code);
            WxMpUser wxMpUser = wxService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            weixinId = wxMpUser.getOpenId();
            request.setAttribute("weixinId", weixinId);

            try {
                UserRegisterService weixinRegisterService = SpringUtil.getBean(UserRegisterService.class);
                //weixinRegisterService.register(wxMpUser);

            } catch (Exception e) {
                log.error("微信自动注册失败：" + e.getMessage());
                e.printStackTrace();
            }
        }


        return getAuthenticationManager().authenticate(new WeixinAuthenticationToken(weixinId));
    }
}
